<template>
  <div class="search-result">
    <div class="search-title flex-col items-start mt-4">
      <tag>
        <span class="font-black"> 与 </span>
        <span class="font-blue"> "自定义股票池" </span>
        <span class="font-black"> 相似的指数 </span>
      </tag>
      <tag class="flex items-center px-1 text-black text-sm ml-48 my-4">
        <span class="flex items-center cursor-pointer"
          ><span>含有自定义股票权重</span><IconSort @click="handleSort('selfStockWeight')"
        /></span>
        <span class="flex items-center cursor-pointer ml-20"
          ><span>含有自定义股票数量比例</span><IconSort @click="handleSort('selfStockRate')"
        /></span>
      </tag>
    </div>
    <div
      v-infinite-scroll="loadMore"
      :infinite-scroll-disabled="disabled"
      :infinite-scroll-distance="10"
      style="overflow-y: auto; max-height: 60vh"
    >
      <div class="result-list" v-for="(item, index) in resultList" :key="index">
        <div class="result-item-title">
          <div class="result-item">
            <div class="result-item-title">
              <span>{{ item.sIrdname }}</span>
            </div>
            <div class="result-item-content">
              <div class="content-title">
                <span class="content-title-left"> 指数代码 </span>
                <span class="content-title-right">{{ item.sIrdcode }}</span>
              </div>
              <div class="content-title">
                <span class="content-title-left">含有自定义股票权重 </span>
                <span class="content-title-right"
                  >{{ item.selfStockWeight ? item.selfStockWeight.toFixed(2) : '--' }}%</span
                >
              </div>
              <div class="content-title" style="display: flex">
                <span class="content-title-left">含有自定义股票数量比例 </span>
                <el-progress
                  :percentage="item.selfStockRate ? item.selfStockRate.toFixed(2) : 0"
                ></el-progress>
              </div>
            </div>
          </div>
          <div class="result-btn" @click="showTable(item)">
            <!--  :disabled="item?.detailsList?.length === 0" -->
            <el-button type="text"
              >{{ item.isActive ? '收起' : '展开' }}查看跟踪ETF
              <span v-if="item.isActive">({{ item?.detailsList?.length }})</span>
            </el-button>
            <!-- :disabled="item?.detailsList?.length === 0" -->
            <el-button type="text" v-if="!item.isActive">
              <Icon icon="iconamoon:arrow-right-2-thin" width="24" height="24" />
            </el-button>
            <!-- :disabled="item?.detailsList?.length === 0" -->
            <el-button type="text" v-else>
              <Icon icon="iconamoon:arrow-down-2-thin" width="24" height="24" />
            </el-button>
            <!--  -->
          </div>
        </div>
        <div class="result-table" v-show="item?.detailsList?.length > 0 && item.isActive">
          <el-table
            :data="item?.detailsList"
            style="width: 100%"
            stripe
            @selection-change="resultSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="sIrdCode" label="ETF代码" align="center" min-width="110">
              <template #default="scope">
                <span
                  class="text-[#2468f2] cursor-pointer"
                  @click="toFundDetail(scope?.row?.sIrdCode)"
                  >{{ scope?.row?.sIrdCode }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="abbrName" label="ETF简称" align="center" min-width="140">
            </el-table-column>
            <el-table-column prop="managementComp" label="基金公司" align="center" min-width="140">
            </el-table-column>
            <el-table-column prop="managerName" label="基金经理" align="center" min-width="140">
            </el-table-column>
            <el-table-column prop="idxType2" label="基金类型" align="center" min-width="110">
            </el-table-column>
            <el-table-column prop="netAsset" label="基金规模" align="center" min-width="110">
              <template #default="scope">
                <span>{{ formatNetAsset(scope?.row?.netAsset) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="setUpDt" label="基金成立日" align="center" min-width="110">
            </el-table-column>
            <el-table-column prop="trackingError" label="跟踪误差" align="center" min-width="110">
              <template #header>
                <el-tooltip effect="light" placement="top" :raw-content="true">
                  <template #content>
                    <div class="formula-tooltip" v-html="renderFormula(trackingErrorFormula)" />
                  </template>
                  <span>跟踪误差</span>
                </el-tooltip>
              </template>
              <template #default="scope">
                <span>{{ fix2(scope?.row?.trackingError) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="sIndexIrdCode"
              label="跟踪指数代码"
              align="center"
              min-width="110"
            >
              <template #default="scope">
                <span class="text-[#2468f2] cursor-pointer" @click="toTrackDetail(scope?.row)">{{
                  scope?.row?.sIndexIrdCode
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sIrdName" label="跟踪指数名称" align="center" min-width="110">
            </el-table-column>
            <el-table-column
              prop="iopvDiscountRate"
              label="IOPV溢折率"
              align="center"
              min-width="110"
            >
              <template #header>
                <el-tooltip
                  popper-class="tooltip-class-blue"
                  effect="light"
                  content="IOPV溢折率 =（二级市场价格/基金份额净值-1) × 100%"
                  placement="top"
                >
                  <span>IOPV溢折率</span>
                </el-tooltip>
              </template>
              <template #default="scope">
                <span>{{ fix2(scope?.row?.iopvDiscountRate) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="volumeMa20"
              label="20日日均成交额"
              align="center"
              min-width="150"
            >
              <template #default="scoped">
                <span>
                  {{ formatAmount(scoped?.row?.volumeMa20 * 1000) }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 加载状态提示 -->
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-if="noMore" class="no-more-text">没有更多数据了</div>
    </div>
    <div
      style="
        height: 70px;
        background-color: rgb(255, 255, 255);
        position: fixed;
        bottom: 0px;
        z-index: 50;
        left: 196px;
        right: 0px;
        max-width: 1300px;
        margin: 0px auto;
      "
      class="flex justify-end items-center"
    >
      <div class="flex items-center mr-6 gap-4">
        <span
          >共选 <span class="text-[#2468f2]"> {{ selectedFundList.length }} </span> 条基金</span
        >
        <div class="cursor-pointer">
          <el-popover placement="top" :width="200" trigger="click">
            <template #reference>
              <span class="text-[#2468f2] ml-2 mr-1">
                详情
                <el-icon :size="14" :color="'#2468f2'"> <ArrowUp /> </el-icon
              ></span>
            </template>
            <el-table :data="selectedFundList" height="204" :show-header="false">
              <el-table-column property="abbrName" label="abbrName" />
            </el-table>
          </el-popover>
        </div>
      </div>
      <div>
        <el-button type="primary" @click="toPortfolioCreate">添加到模拟组合</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getW1055049, getHanger } from '@/api/etfpegging.js'
import { Icon } from '@iconify/vue'
import IconSort from '@/assets/img/sort.svg?component'
import eventBus from '@/utils/eventBus'
import { ElMessage } from 'element-plus'
import routerParent from '@/utils/router/routerParent/index'
import katex from 'katex'
import 'katex/dist/katex.min.css'
const indexList = ref([])
const resultList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const orderFlag = ref(0)
const orderField = ref('selfStockWeight')
const weightOrderFlag = ref(0)
const rateOrderFlag = ref(0)
const disabled = computed(() => loading.value || noMore.value)
const noMore = computed(() => resultList.value.length >= total.value)
//选中基金列表
const selectedFundList = ref([])

const resultSelectionChange = (selectedRows) => {
  // 遍历当前选中的行
  selectedRows.forEach((selectedRow) => {
    // 检查选中的行是否已经在 selectedFundList 中
    const exists = selectedFundList.value.some((fund) => fund.sIrdCode === selectedRow.sIrdCode)
    // 如果不在 selectedFundList 中，则添加
    if (!exists) {
      selectedFundList.value.push(selectedRow)
    }
  })
}
//携带数据跳转到组合创建页面
const toPortfolioCreate = () => {
  if (selectedFundList.value.length === 0) {
    ElMessage.warning('请先选择要添加的组合信息！')
    return
  }
  const encodedFundList = encodeURIComponent(JSON.stringify(selectedFundList.value))
  routerParent(`/portfolioCreate?selectedFundLists=${encodedFundList}`)
}

const trackingErrorFormula = String.raw`
{\color{#2468f2}基金误差 = \sqrt{\frac{1}{N-1}\sum{_{t=1}^{N}}\left(基金日度收益率-跟踪指数日度收益率 \right) ^2}\times\sqrt{252}}
`
const renderFormula = (formula) => {
  try {
    return katex.renderToString(formula, {
      throwOnError: false,
      displayMode: true,
      output: 'mathml',
    })
  } catch (e) {
    console.error('KaTeX render error:', e)
    return formula
  }
}
//跳转到基金详情
const toFundDetail = (code) => {
  routerParent(`/EtfFundDetails?sIrdCode=${code}`)
}

const toTrackDetail = (row) => {
  const sIndexIrdCode = row.sIndexIrdCode
  const sIrdname = row.sIrdName
  routerParent(`/trackerDetail?sIrdCode=${sIndexIrdCode}&sIrdName=${encodeURIComponent(sIrdname)}`)
}

const showTable = async (item) => {
  item.isActive = !item.isActive // 切换当前项的 isActive 状态
  // 当前项的 isActive 状态为 true，请求获取详情数据
  // datailsList已经有数据就不在发生接口请求
  if (item.isActive && item.detailsList.length > 0) {
    return
  }
  if (item.isActive) {
    const params = {
      sIrdCode: item.sIrdcode,
    }
    const res = await getHanger(params)
    if (res?.data) {
      item.detailsList = res.data
    }
  }
}

const emit = defineEmits(['dataComplete'])
const getData = async (indexCustomerList, isParent) => {
  if (isParent) {
    //如果是父组件调用，则indexList从父组件传过来及pageNum需要重置1
    indexList.value = indexCustomerList.map((item) => item?.sConIrdcode)
    pageNum.value = 1
  }
  const params = {
    strings: indexList.value,
    currentPage: pageNum.value,
    pageSize: pageSize.value,
    orderField: orderField.value,
    orderFlag: orderFlag.value,
  }
  loading.value = true
  try {
    const res = await getW1055049(params)
    if (res?.data?.records) {
      total.value = res.data.total
      const result = res.data.records.map((item) => ({
        ...item,
        isActive: false,
        detailsList: [],
      }))
      if (1 === pageNum.value) {
        resultList.value = result
      } else {
        resultList.value = [...resultList.value, ...result]
      }
      //通知父组件调用完成
      emit('dataComplete', resultList.value)
    } else {
      ElMessage.error('暂无数据！')
    }
  } finally {
    loading.value = false
  }
}
defineExpose({ getData })

const loadMore = () => {
  if (noMore.value || !indexList.value || loading.value) return
  pageNum.value++
  getData(indexList.value)
}
const formatNetAsset = (val) => {
  if (!val) return '--'
  return (val / 100000000).toFixed(2) + '亿'
}
const fix2 = (val) => {
  if (val === 0) return '0'
  if (!val) return '--'
  return (val * 100).toFixed(2) + '%'
}
const formatAmount = (val) => {
  if (val == null) return '--'

  const formatWithCommas = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }

  if (val >= 1e8) return formatWithCommas((val / 1e8).toFixed(2)) + '亿'
  if (val >= 1e4) return formatWithCommas((val / 1e4).toFixed(2)) + '万'
}

// 重置resultlist
const resetResultList = () => {
  resultList.value = []
}

const handleSort = (field) => {
  if ('selfStockWeight' === field) {
    weightOrderFlag.value = 0 === weightOrderFlag.value ? 1 : 0
    orderFlag.value = weightOrderFlag.value
  } else {
    rateOrderFlag.value = 0 === rateOrderFlag.value ? 1 : 0
    orderFlag.value = rateOrderFlag.value
  }
  orderField.value = field
  //重置分页
  pageNum.value = 1
  pageSize.value = 10

  getData(indexList.value)
}

// 监听event
onMounted(() => {
  eventBus.on('resetResultList', resetResultList)
  eventBus.on('resetSelectedList', resetSelectedList)
})

onUnmounted(() => {
  eventBus.off('resetResultList', resetResultList)
  eventBus.off('resetSelectedList', resetSelectedList)
})

const resetSelectedList = () => {
  selectedFundList.value = []
}
</script>

<style lang="scss" scoped>
.search-result {
  // overflow-y: scroll;
  margin: 0 20px;
  .search-title {
    .font-black {
      font-family: Source Han Sans CN;
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }

    .font-blue {
      font-family: Source Han Sans CN;
      font-size: 18px;
      font-weight: 500;
      color: #2468f2;
    }
  }
  .result-list {
    background: linear-gradient(360deg, #ffffff 50%, #f1f6ff 100%);
    border: 1px solid #dde6f6;
    border-radius: 8px;
    justify-content: space-between;
    margin-bottom: 20px;
    .result-item-title {
      display: flex;
      justify-content: space-between;
      .result-item {
        .result-item-title {
          span {
            margin: 10px 0px 4px 10px;
            font-family: Source Han Sans CN;
            font-size: 18px;
            font-weight: 500;
            color: #2468f2;
          }
        }
        .result-item-content {
          display: flex;
          margin: 0 0 10px 10px;
          .content-title {
            margin-right: 40px;
            .content-title-left {
              font-family: Source Han Sans CN;
              font-size: 14px;
              font-weight: 350;
              margin-right: 4px;
              color: #7b7f8d;
            }
            .content-title-right {
              font-family: Source Han Sans CN;
              font-size: 14px;
              font-weight: 500;

              color: #333333;
            }
          }
          :deep(.el-progress) {
            display: flex;
            align-items: center;
            width: 220px;
          }
        }
      }
      .result-btn {
        display: flex;
        margin: 0 20px;
        align-items: center;
        :deep(.el-button:hover) {
          border-color: transparent;
          background-color: transparent;
        }
        .svg-icon {
          font-size: 20px;
        }
        :deep(.el-button:focus) {
          color: #2468f2;
          border-color: transparent;
          background-color: transparent;
        }
      }
    }
    .result-table {
      margin: 15px 10px;
    }
  }
}
/* 新增样式 */
.loading-text,
.no-more-text {
  padding: 10px;
  text-align: center;
  color: #999;
}
</style>
<style>
.tooltip-class-blue {
  color: #2468f2;
  font-size: 13px;
}
</style>
